package com.late13.myapplication;

import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.ActionBar;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;

import org.litepal.LitePal;

import java.text.ParseException;
import java.util.Calendar;
import java.util.Date;

public class Editor extends AppCompatActivity {

    public static final int RESULT_CHANGED = 1;
    private Task mTask = null;
    private static final String TAG = MainActivity.MAIN_TAG + "Editor";

    EditText title;
    CheckBox checkBox;
    EditText content;
    TextView dateText;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_editor);
        Intent intent = getIntent();
        int id = intent.getIntExtra("id", -1);

        Toolbar toolbar = findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        ActionBar actionBar = getSupportActionBar();
        if(actionBar != null) {
            actionBar.setDisplayHomeAsUpEnabled(true);
        }

        title = findViewById(R.id.editor_title_edit);
        checkBox = findViewById(R.id.editor_checkbox);
        content = findViewById(R.id.editor_content_edit);
        dateText = findViewById(R.id.editor_date_text);
        Button dateSelect = findViewById(R.id.editor_date_btn);

        Log.d(TAG, "editor正在启动，id为" + id);
        if (id != -1) {
            mTask = getDBTask(id);
            title.setText(mTask.getTaskTitle());
            checkBox.setChecked(mTask.isTaskFinished());
            content.setText(mTask.getTaskContent());
            if(mTask.getDueDate() == null) {
                dateText.setText(Task.DATE_DEFAULT_STRING);
            } else {
                dateText.setText(Task.DATE_FORMAT.format(mTask.getDueDate()));
            }
        } else {
            Log.v(TAG, "id为-1，准备新建task");
            mTask = new Task();
        }

        dateSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePicker=new DatePickerDialog(Editor.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        String dateStr = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
                        dateText.setText(dateStr);
                    }
                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                datePicker.setButton(DatePickerDialog.BUTTON_NEUTRAL, "无日期", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dateText.setText(Task.DATE_DEFAULT_STRING);
                    }
                });
                datePicker.show();
            }
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            quitEditor();
        }
        return super.onKeyDown(keyCode, event);
    }

    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.toolbar_editor, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case android.R.id.home:
                Log.v(TAG, "home pressed!");
                quitEditor();
                return true;
            case R.id.toolbar_cancel:
                finish();
                return true;
        }
        return super.onOptionsItemSelected(item);
    }

    private void quitEditor() {
        if (isContentChanged()) {
            if(saveContent(mTask.getTaskId())) {
                finish();
            }
        }else {
            finish();
        }
    }

    protected boolean isContentChanged(){
        Log.v(TAG, "若内容已保存，返回false，若内容被修改而未保存，返回true");
        if(mTask.getTaskId() == -1) {
            if("".equals(title.getText().toString()) && "".equals(content.getText().toString())) {
                return false;
            }
        } else {
            Log.d(TAG, "读取内存，和当前数据比对，若不一致则为已更改");
            if(title.getText().toString().equals(mTask.getTaskTitle())
                    && checkBox.isChecked() == mTask.isTaskFinished()
                    && content.getText().toString().equals(mTask.getTaskContent())
                    && dateText.getText().toString().equals(mTask.getDueDate())) {
                return false;
            }
        }
        return true;
    }

    protected boolean saveContent(int id){
        Log.v(TAG, "保存数据到数据库");
        TaskInDB taskInDB = new TaskInDB();

        String sTitle = title.getText().toString().trim();
        if(sTitle.isEmpty()) {
            Toast.makeText(this, "标题不能为空！", Toast.LENGTH_SHORT).show();
            return false;
        }
        taskInDB.setTitle(sTitle);
        taskInDB.setContent(content.getText().toString());
        if(checkBox.isChecked()) {
            taskInDB.setFinished(true);
        } else {
            taskInDB.setToDefault("finished");
        }

        Log.v(TAG, "保存日期");
        String dateStr = dateText.getText().toString();
        Date date = null;
        try {
            date = Task.DATE_FORMAT.parse(dateStr);
            taskInDB.setDueDate(date);
        } catch (ParseException e) {
            Log.d(TAG, "ParseException, 将日期设置为无期限");
            taskInDB.setToDefault("dueDate");
        }

        if(-1 == id) {
            taskInDB.save();
//            mTask.setTaskId(taskInDB.getId());
        } else {
            taskInDB.update(id);
        }
        setResult(RESULT_CHANGED);
        Toast.makeText(this, "更改已保存", Toast.LENGTH_SHORT).show();
        return true;
    }

    protected Task getDBTask(int id) {
        Log.v(TAG, "准备读取数据库中id为" + id + "的数据");
        TaskInDB taskInDB = LitePal.find(TaskInDB.class, id);
        Task task;
        String title = taskInDB.getTitle();
        String content = taskInDB.getContent();
        boolean isFinished = taskInDB.getFinished();
        Date date = taskInDB.getDueDate();
        task = new Task(id, title, isFinished, date);
        task.setTaskContent(content);
        return task;
    }
}
